package cn.jofei.common.monitor.interf;

import cn.jofei.common.config.AppProperties;
import cn.jofei.common.monitor.msg.DingMsg;

import java.text.DecimalFormat;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Monitor
 *
 * @author Jofei Bao
 * @version ngbao v1.0.
 * @date 2022年10月25日 18:28
 */
public abstract class Monitor implements Runnable {

    protected String monitName;

    protected Boolean ok = true;

    /**
     * 执行周期
     */
    private final int period = AppProperties.get("monitor.period", Integer.class).orElse(60);

    protected static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("MM月dd日 HH点mm分ss秒");

    protected static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("######0.00");

    private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = new ScheduledThreadPoolExecutor(2);

    /**
     * 获取监控结果，监控结果正常则返回: null
     *
     * @return
     */
    protected abstract DingMsg getMsg();

    protected Boolean isOk() {
        return ok;
    }

    protected void setOk(Boolean ok) {
        this.ok = ok;
    }

    public void reg() {
        SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(this, 0, period, TimeUnit.SECONDS);
    }

    @Override
    public void run() {
        DingMsg dingMsg = getMsg();
        if (dingMsg != null) {
            dingMsg.send();
        }
    }
}
